# pip install pyDes
import pyDes
import base64
import time
import hashlib

class Crypto_tdes(): #初始化key
    def __init__(self, key):
        self.key=key.encode("utf8")
        
    def encrypt(self, s):
        """
        3DES 加密
        :param s: 原始字符串
        :return: 加密后字符串，16进制
        """
        k = pyDes.triple_des(self.key)

        input_text = s.encode("utf8")
        if len(input_text) > 100:
            input_text_1 = input_text[:79]
            input_text_2 = input_text[79:]
            en = k.encrypt(input_text_1, padmode=pyDes.PAD_PKCS5)
            en = en + input_text_2
        else:
            en = k.encrypt(input_text, padmode=pyDes.PAD_PKCS5)

        return str(base64.b64encode(en), 'utf-8')

    def descrypt(self, s):
        """
        3DES 解密
        :param s: 加密后的字符串，16进制
        :return:  解密后的字符串
        """
        k = pyDes.triple_des(self.key)

        input_text = base64.b64decode(s)
        if (len(input_text) >= 80):
            input_text_1 = input_text[:80]
            input_text_2 = input_text[80:]
            de = k.decrypt(input_text_1, padmode=pyDes.PAD_PKCS5)
            de = de + input_text_2
        else:
            de = k.decrypt(input_text, padmode=pyDes.PAD_PKCS5)
        return de

if __name__ == "__main__":
    t = time.time()
    t = str(int(t*1000000))

    obj = hashlib.md5()
    obj.update(t.encode("utf-8"))
    result=obj.hexdigest()

    key = result.upper()[:16]
    print(key)
    ender = Crypto_tdes(key)
    #en = ender.encrypt("112345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890234567890")
    #en = ender.encrypt("123456781234567")
    #de = ender.descrypt(en)
    #print(len(en))
    #print(en)
    #print(str(de, 'utf-8'))

    with open('test.json') as f:
        data = f.read()
        en = ender.encrypt(data)
        de = ender.descrypt(en)
        de_str = str(de, 'utf-8')

    with open('test_out.txt', "w", encoding='utf-8') as f:
        f.write(en)
